package server;

import channel.WebSocketChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

/**
 * @author yuzk
 * @date 2018/1/22
 */
public class WebSocketServer {

    public static final String IP = "localhost";
    public static final int PORT = 9999;

    private static final ChannelGroup GROUP = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    private final EventLoopGroup workerGroup  = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture start(){
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketChannelInitializer(GROUP));
        ChannelFuture f = bootstrap.bind(IP,PORT).syncUninterruptibly();
        channel = f.channel();
        return f;
    }

    public void run(){
        ChannelFuture f = start();
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                serverDestroy();
            }
        });
        f.channel().closeFuture().syncUninterruptibly();
    }
    public void serverDestroy() {
        if(channel != null){
            channel.close();
        }
        GROUP.close();
        workerGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        final WebSocketServer socketServer = new WebSocketServer();
        socketServer.run();
    }
}
